package top.kikt.book.core.handlers

import org.jsoup.nodes.Document
import top.kikt.book.core.entity.BookMetaEntity
import top.kikt.book.core.entity.ChapterEntity
import top.kikt.book.core.entity.ChapterMetaEntity
import top.kikt.book.core.handlers.common.BaseBookHandler
import top.kikt.book.util.HttpUtils
import top.kikt.book.util.HttpUtils.string
import top.kikt.book.util.bookText
import top.kikt.book.util.metaContentWithProperty

/**
 * http://www.qudushu.com/
 */
class QuDuShu : BaseBookHandler() {

    override val host: String
        get() = "www.qudushu.com"

    override val hosts: List<String>
        get() = listOf("www.qudushu.com", "www.quduwx.org", "www.qudushu.org", "www.qudushu.info")

    @Suppress("unused")
    private fun String.trimSomeString(): String {
        return this.replace("《", "").replace("》", "")
    }

    override fun parseBookMeta(document: Document, url: String): BookMetaEntity {
        val name = document.metaContentWithProperty("og:novel:book_name")
        val author = document.metaContentWithProperty("og:novel:author")
        val coverUrl = document.metaContentWithProperty("og:image")
        val menuUrl = document.metaContentWithProperty("og:novel:read_url")
        return BookMetaEntity(name, url, menuUrl, author, coverUrl)
    }

    override fun parseChapterMeta(document: Document, menuUrl: String): List<ChapterMetaEntity> {
        val arrayList = ArrayList<ChapterMetaEntity>()

        val chapterElements = document.select(".chapters .chapter")

        var index = 0

        for (chapter in chapterElements) {
            val aElement = chapter.select("a").first()!!
            val url = aElement.attr("href")
            val title = aElement.text().trim()
            index++
            val chapterMeta = ChapterMetaEntity(title, index, url, chapter)
            arrayList.add(chapterMeta)
        }

        return arrayList
    }

    override fun parseChapter(chapterMetaEntity: ChapterMetaEntity): ChapterEntity? {
        val name = "第${chapterMetaEntity.index}章 ${chapterMetaEntity.name}"

        val doc = HttpUtils.get(chapterMetaEntity.url).string(charset)?.toDocument() ?: return null

        val content = doc.getElementById("acontent")!!
        val text = content.bookText()

        return ChapterEntity(name, chapterMetaEntity.index, text)
    }

    // 开头有(去读书 www.quduwx.org)， 结尾有

    override fun watermark(): Map<Regex, String> {
        return mapOf(
            Regex("[(]*去读书 www.quduwx.org[)]*") to "",
            Regex("[(]*去读书 www.qudushu.org[)]*") to "",
            Regex("[(]*去读书 www.qudushu.info[)]*") to "",
        )
    }
}
